<template>
	<view class="container">
			<view class="exam-paper-content" v-if="!SumitState">
				<view class="exam-header">
					<view class="exam-number">
						<text class="this-num">{{examData.number.thisNum}}.</text>
					</view>
					<view class="exam-type">
						<text>{{examData.questionType}}</text>
						<view class="btn">
							<image src="../../../../static/icons/store.png" mode="" class="collection" @click="changeImg" v-show="showUpImg"></image>
							<image src="../../../../static/icons/store1.png" mode="" class="collection" @click="changeImg" v-show="!showUpImg"></image>
						</view>
					</view>
				</view>
			
				<view class="exam-question">
					<text>{{examData.question}}</text>
				</view>
			
				<view class="exam-radio">
					<view class="exam-option"  v-for="(item, index) in examData.options" @click="chooseOption" :data-val="item.val"  :key="index" >
						<text class="chooseVal" :class="examData.choose==item.val ? 'active' : ''" 
						>{{item.val}}</text> 
						<text>{{item.content}}</text>
					</view>
				</view>
			</view>
			
			<view class="footer" v-if="!SumitState">
					<view class="btn prev" @click="onPreQuestion" v-if="examData.number.thisNum>1">
					    <image src="../../../../static/icons/prev.png" mode=""></image>
						<text>上一题</text>
					</view>
					<view class="exam-number">
						<text class="this-num">{{examData.number.thisNum}}</text>
						<text style="margin: 0 5rpx;">/</text>
						<text>{{examData.number.allNumber}}</text>
						<text class="answer">答题卡</text>
					</view>
					<view class="btn next" @click="onNextQuestion" v-if="examData.number.thisNum < examData.number.allNumber">
						<text>下一题</text>
						<image src="../../../../static/icons/next.png" mode=""></image>
					</view>
					<view class="btn submit" @click="onSumbitExam" v-else>
						<image src="../../../../static/icons/submit.png" mode=""></image>
						<text>提交试卷</text>
					</view>
				</view>
		<view class="score" v-else>
			得分: <h2>{{totalScore}}</h2>
			
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				SumitState:false,
				showUpImg:true,
				allData:[],
				resultList:[],
				/**
				 * {id,value}
				 * */
				examData: {
					isFav: false,
					number: {
						thisNum: 1,
						allNumber: 2
					},
					questionType: '',	
					question: '',
					choose: '',
					options: [
					],
					
					
					
					
				}
			};
		},
		methods: {
			
			
			// chooseOption(){
			// 	console.log(this)
				
			// },
			
			/**
			 * 
			 * 获取所有题目数据
			 * */
			async getListData(){
				let response=await fetch('http://xuyifeitest.natapp1.cc/titleTest')
				response=await response.json();
				this.allData=response.data;
				this.examData.number.allNumber=this.allData.length;
				this.formatQuestion();
				// this.examData.options=[response.data[this.examData.number.thisNum-1]];
				// then(res=>{
				// 	return res.json()
				// }).then(res=>{
				// 	console.log(res);
				// })
			},
			/**
			 * 
			 * 收集处理答案数据
			 * */
			collectRes(){
				let index=this.examData.number.thisNum-1;
				let {id}=this.allData[index];
				// console.log(id,'iddddd');
				let correct=this.examData.choose
				let target=this.resultList.filter(v=>v.id==id)
				if(target.length){
					target[0].correct=correct;
				}else{
					this.resultList.push({id,correct})
				}
				
			},
			/**
			 * 
			 * 生成当前题目
			 * */
			formatQuestion(){
				let id=this.examData.number.thisNum;
				const q=this.allData[id-1];
				let targetArr=this.resultList.filter(v=>v.id==id)
				let choose=targetArr.length?targetArr[0].correct:'';
				this.examData.choose=choose;
				this.examData.question=q.question;
				this.examData.options=[];
				for(const key in q){
					if(key.includes('anwser')){
						let str=q[key];
						if(!str)continue;
						let dot = str.includes('.')?'.':str.includes('．')?'．':'';
						let arr=str.split(dot)
						let content=arr[1].trim().replace(/<br>/gi,'');
						let val=arr[0].trim();
						// console.log({content,val},'处理结果');
						this.examData.options.push({content,val});
					}
				}
			},
			onPreQuestion(){
				this.examData.number.thisNum-=1;
				this.formatQuestion();
				// this.examData = {
				// 	isFav: false,
				// 	number: {
				// 		thisNum: 1,
				// 		allNumber: 2
				// 	},
				// 	questionType: '单选题',
				// 	question: '"感时花溅泪"下一句是什么？()',
				// 	choose: 'A',
				// 	options: [{
				// 		content: '也无风雨也无晴',
				// 		val: 'A'
				// 	}, {
				// 		content: '明月即使有',
				// 		val: 'B'
				// 	}, {
				// 		content: '恨别鸟惊心',
				// 		val: 'C'
				// 	}, {
				// 		content: '只识弯弓射大雕',
				// 		val: 'D'
				// 	}]
				// }
			},
			onNextQuestion(){
				this.examData.number.thisNum+=1;
				this.formatQuestion()
				// this.examData = {
				// 	isFav: false,
				// 	number: {
				// 		thisNum: 2,
				// 		allNumber: 2
				// 	},
				// 	questionType: '单选题',
				// 	question: '"恨别鸟惊心"上一句是什么？()',
				// 	choose: 'A',
				// 	options: [{
				// 		content: '也无风雨也无晴',
				// 		val: 'A'
				// 	}, {
				// 		content: '明月即使有',
				// 		val: 'B'
				// 	}, {
				// 		content: '恨别鸟惊心',
				// 		val: 'C'
				// 	}, {
				// 		content: '只识弯弓射大雕',
				// 		val: 'D'
				// 	}]
				// }
			},
			chooseOption(e) {
				this.examData.choose = e.currentTarget.dataset.val;
				this.collectRes();
			},
			changeImg(){
				this.showUpImg = !this.showUpImg 
			},
			onSumbitExam(){
				if(confirm('确定提交考试吗？')){
					this.SumitState=true;
					//2023.3.21
					    // let sum=0
					    // let ansLen=this.allData.length;
					    // let userAnswers = [];
					    // for (let index=0;index<ansLen;index++) {
					    //   let id=index+1;
					    //   let targetArr=this.resultList.filter(v=>v.id==id);
					    //   if(!targetArr.length){
					    //     continue;
					    //   }
					    //   let {correct}=this.allData[index];
					    //   if(correct==targetArr[0].value){
					    //     sum+=1;
					    //   }
					    //   userAnswers.push({id:id,correct: targetArr[0].value});
					    // }
					
					    // 将JSON数据发送到指定端口
					    fetch('http://xuyifeitest.natapp1.cc/answerResult', {
					      method: 'POST',
					      headers: {
					        'Content-Type': 'application/json'
					      },
					      body: JSON.stringify(this.resultList)
					    })
					    .then(response => {
					      if (response.ok) {
					        console.log('JSON数据已发送到服务器');
							console.log(userAnswers)
					      } else {
					        console.error('发送JSON数据时出错');
					      }
					    })
					    .catch(error => {
					      console.error('发送JSON数据时出错:', error);
					    });
					
					 // return sum;
				}
				
				// uni.showModal({
				// 	title: '提示',
				// 	content:"确定提交考试吗？",
				// 	success:function(res){
				// 			if (res.confirm) {
				// 				this.SumitState=true;
				// 				console.log(this.SumitState,'state');
				// 				// uni.navigateBack({
				// 				// 	delta: 1
				// 				// })
				// 			} 
				// 		}
				// })
			},
			onQuitExam(){
				uni.showModal({
					title: '提示',
					content:"确定退出考试吗？",
					success: function (res) {
							if (res.confirm) {
								uni.navigateBack({
									delta: 1
								})
							} 
						}
				})
			}
		},
		mounted() {
			this.getListData()
		},
		
		
	
		//收集答案
		computed:{
			totalScore(){
				let sum=0
				let ansLen=this.allData.length;
				let answerResults = [];
				for (let index=0;index<ansLen;index++) {
					let id=index+1;
					let targetArr=this.resultList.filter(v=>v.id==id);
					if(!targetArr.length){
						continue;
					}
					let {correct}=this.allData[index];
					if(correct==targetArr[0].value){
						sum+=1;
					}
					
					
					
					
					// const answers = this.allData.map((q, index) => ({
					//   id: index + 1,
					//   correct: this.resultList.find(v => v.id === index + 1)?.value
					// }));
					
					// fetch('http://xuyifeitest.natapp1.cc/answerResult', {
					//   method: 'POST',
					//   headers: {
					//     'Content-Type': 'application/json'
					//   },
					//   body: JSON.stringify({ answers })
					// })
					//   .then(response => response.json())
					//   .then(data => console.log(data))
					//   .catch(error => console.error(error))
					
					
					
					
					
					
					//控制台可以拿到用户提交的的答案数组
					//   let sum = 0
					//     let ansLen = this.allData.length;
					//     let userAnswers = [];
					//     for (let index = 0; index < ansLen; index++) {
					//       let id = index + 1;
					//       let targetArr = this.resultList.filter(v => v.id == id);
					//       if (!targetArr.length) {
					//         continue;
					//       }
					//       let {correct} = this.allData[index];
					//       if (correct == targetArr[0].value) {
					//         sum += 1;
					//       }
					//       userAnswers.push({id: id, correct: targetArr[0].value});
					//     }
					//     console.log(JSON.stringify(userAnswers));
					
					
					
					
					
					
					
					
				}
				
			}
		}
	}
	
	

	
	 

</script>
<style>
	page {
		background-color: #F8F8F8;
		
		letter-spacing: 1px;
	}
</style>
<style lang="scss" scoped>
	.container{
		padding-top: 30rpx;
		font-family: Arial, Verdana, "Microsoft Yahei","Pingfang SC", Simsun;
	}
	.score{
		height: calc(100vh - 100px);
		width: 100%;
	}
	.exam-paper-content {
		padding-left: 20px;
		padding-right: 20px;
		margin: 10px;
		.exam-header {
			display: flex;
			align-items: center;
			height: 60rpx;
			line-height: 60rpx;
			.exam-number {
				font-size: 16px;
				.this-num {
					color: #a7a7a7;
				}
			}

			.exam-type {
				margin-left: 16rpx;
				height: 40px;
				line-height: 40px;
				color:  #a7a7a7;
				width: 100%;
				text{
					display: inline-block;
					float: left;
				}
				.btn{
					float: right;
					.collection{
						width: 20px;
						height: 20px;
						vertical-align: middle;
					}
				}
			}
		}

		.exam-question {
			margin: 20px 0 90px ;
		}
		.exam-radio {
			margin-bottom: 50px;
			
			.exam-option {
				min-height: 20px;
				line-height: 1.4em;
				padding: 22rpx 30rpx;
				border-radius: 60rpx;
				margin-bottom: 22rpx;
				display: flex;
				align-items: center;
				.chooseVal{
					border: 1px solid #229DDD;
					width: 30px;
					height: 30px;
					border-radius: 50%;
					display: inline-block;
					text-align: center;
					color:#229DDD;
					margin-right: 10px;
					flex-shrink: 0;
					line-height: 30px;
				}
				.active {
					background:#229DDD ;
					border: 1px solid #fff;
					color: #fff;
				}
			}
			
		}

	}
	
	.score {
		
		
		
	}
	
	
	
	
	.footer {
		height: 50px;
		background: #fff;
		margin: 20px 15px 0 15px;
		border-radius: 10px;
		padding-left: 10px;
		padding-right: 10px;
		font-size: 14px;
		color: #229DDD;
		position: relative;
		box-shadow: 0 3px 2px  0 #dedede;
		.exam-number{
			float: left;
			height: 50px;
			width: 50px;
			position: absolute;
			left: 280rpx;
			top:5px;
			text-align: center;
			.answer{
				
				display:inline-block;
			}
		}
		.next {
			float: right;
			line-height: 50px;
			text{
				display: inline-block;
				margin-right:5px ;
			}
		}
		.prev{
			float: left;
			line-height: 50px;
				text{
					display: inline-block;
					margin-left:5px ;
				}
			}
		image{
			width: 10px;
			height: 10px;
		}
		.submit{
			float: right;
			line-height: 50px;
			text{
				
				display: inline-block;
				margin-left:5px ;
			}
			image{
				width: 15px;
				height: 15px;
				display: inline-block;
				vertical-align: middle;
			}
		}
			
	
	}
</style>
